$(document).ready(function(){

    $(".menu_item").each(function() {
        $(this).hover(
                function() {
                    if (!$(this).hasClass("selected_menu_item")) {
                        $(this).addClass("menu_item_hover");
                    }
                },
                function(){
                    $(this).removeClass("menu_item_hover");
                }
        );
    });
    $(".active_daymenu").each(function() {
        $(this).hover(
                function() {
                    $(this).addClass("active_daymenu_hover");
                },
                function(){
                    $(this).removeClass("active_daymenu_hover");
                }
        );
    });
    $(".cur_active_daymenu").each(function() {
        $(this).hover(
                function() {
                    $(this).addClass("active_daymenu_hover");
                },
                function(){
                    $(this).removeClass("active_daymenu_hover");
                }
        );
    });
    $("input.onlyNumbers").keydown(function(event) {
        // Allow: backspace, delete, tab, escape, and enter
        if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
            // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) ||
            // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault();
            }
        }
    });


    var onResizeHandler = function () {
        $("#main_area_block").css("height", document.body.clientHeight - 40 > 600 ? document.body.clientHeight - 40 : 600);
    };
//    window.onresize = onResizeHandler;
    $(window).resize(onResizeHandler);
    onResizeHandler();

});

function makeHover(selector, hoverClass) {
    $(selector).hover(function() {
        $(this).addClass(hoverClass);
    }, function() {
        $(this).removeClass(hoverClass);
    });
}

function showLoadingDialog() {

    var loadingDialog = $("#loading_dialog");
    if (!loadingDialog.length) {
        loadingDialog = $("<div id='loading_dialog'><img src='img/loading.gif' style='text-align:center;' width='100%' height='100%' /></div>");
        loadingDialog.appendTo(document.body);
    }

    loadingDialog.dialog({
        "modal":true,
        "resizable":false,
        "title": 'loading',
        minHeight: 300,
        minWidth: 300,
        closeOnEscape: false,
        draggable: false,
        position: ['center', 'center'],
        open : function(event, ui) {
            $(".ui-dialog-titlebar").hide();
        },
        close : function(event, ui) {
            $(".ui-dialog-titlebar").show();
        }
    });

}

function hideLoadingDialog() {
    $("#loading_dialog").dialog("destroy");
}

function addExistingRecipeToEatingMenu(url, recipeId, usersTableId, dayMenuId, eatingMenuId, addRecipeCallback) {
    showLoadingDialog();
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        data: {
            "recipeId": recipeId,
            "usersTableId": usersTableId,
            "dayMenuId": dayMenuId,
            "eatingMenuId": eatingMenuId
        },
        success: function(reply) {
            if (reply) {
                if (reply.error) {
                    alert('error:' + reply.error);
                    window.location.reload(true);
                } else {
                    addRecipeCallback(reply);
                    hideLoadingDialog();
                }
            } else {
                alert("Server error");
                window.location.reload(true);
            }
        },
        error: function(error) {
            alert(error);
            window.location.reload(true);
        }
    });
}

function updateEatingMenuRecipeCount(url, eatingMenuRecipeId, count, usersTableId, dayMenuId, eatingMenuId, updateCountHandler) {
    showLoadingDialog();
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        data: {
            "eatingMenuRecipeId": eatingMenuRecipeId,
            "count": count,
            "usersTableId": usersTableId,
            "dayMenuId": dayMenuId,
            "eatingMenuId": eatingMenuId
        },
        success: function(reply) {
            if (reply) {
                if (reply.error) {
                    alert('error:' + reply.error);
                    window.location.reload(true);
                } else {
                    updateCountHandler(reply);
                    hideLoadingDialog();
                }
            } else {
                alert("Server error");
                window.location.reload(true);
            }
        },
        error: function(error) {
            alert(error);
            window.location.reload(true);
        }
    });
}

function removeRecipeFromEatingMenu(url, eatingMenuRecipeId, usersTableId, dayMenuId, eatingMenuId, removeCallback) {
    showLoadingDialog();
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        data: {
            "id": eatingMenuRecipeId,
            "usersTableId": usersTableId,
            "dayMenuId": dayMenuId,
            "eatingMenuId": eatingMenuId
        },
        success: function(reply) {
            if (reply) {
                if (reply.error) {
                    alert('error:' + reply.error);
                    window.location.reload(true);
                } else {
                    removeCallback(reply);
                    hideLoadingDialog();
                }
            } else {
                alert("Server error");
                window.location.reload(true);
            }
        },
        error: function(error) {
            alert(error);
            window.location.reload(true);
        }
    });
}

function WaresSelectDialog(wareDialogContainerId, selectWaresFormUrl, getWaresListUrl) {

    var thisObj = this;

    var wareDialogContainerSelector = "#" + wareDialogContainerId;

//    var onWareDialogLinkClick = function(ingredientId, callbackHandler) {
    this.onWareDialogLinkClick = function(ingredientId, callbackHandler) {
        $(wareDialogContainerSelector).dialog({
            "modal":true,
            "resizable":false,
            "title": 'select ware',
            minHeight: 450,
            minWidth: 650
        });
        if (ingredientId) {
            loadWaresForIngredient(ingredientId, callbackHandler, 0);
        } else {
            $.ajax({
                url: selectWaresFormUrl,
                type: 'GET',
                dataType: 'json',
                success: function(reply) {
                    if (reply) {
                        if (reply.error) {
                            alert('error:' + reply.error);
                        } else {
                            //alert(reply['formHtml']);
                            var containerPtr = $(wareDialogContainerSelector);
                            containerPtr.html(reply['formHtml']);

                            $("#wares_group_browser").treeview();

                            $(".folder").unbind("click.treeview").add($("a", this)).hoverClass();

                            $(".folder").each(function() {
                                var groupId = $(this).children(".hidden_id").text();
                                $(this).click(function() {
                                    onWaresGroupSelect(callbackHandler, groupId, 0);
                                });
                            });
                        }
                    } else {
                        alert("Server error");
                    }
                },
                error: function(error) {
                    alert(error);
                    window.location.reload(true);
                }
            });
        }
        //alert("show dialog");
    };

    var loadWaresForIngredient = function(ingredientId, callbackHandler, page) {
        $.ajax({
            url: getWaresListUrl,
            type: 'GET',
            dataType: 'json',
            data: { "ingredientId": ingredientId, "page": page },
            success: function(reply) {
                if (reply) {
                    if (reply.error) {
                        alert('error:' + reply.error);
                    } else {
                        //alert(reply['formHtml']);
                        var containerPtr = $(wareDialogContainerSelector);
                        containerPtr.html(reply['formHtml']);
                        var waresViews = reply['waresViews'];

                        $(".ware_select_link").each(function() {
                            var wareId = $(this).children(".hidden_id").text();
//                            var wareName = $(this).children(".ware_name").text();
                            $(this).click(function() {
                                //alert("selected ware with ID: " + wareId);
//                                callbackHandler(wareId, wareName);
                                callbackHandler(waresViews[wareId]);
                                $(wareDialogContainerSelector).dialog("destroy");
                            });
                            $(this).hover(function() {
                                $(this).addClass("hover_link");
                            }, function() {
                                $(this).removeClass("hover_link");
                            });
                        });
                        $(".page_select_link").each(function() {
                            var pageNum = $(this).children(".hidden_id").text();
                            $(this).click(function() {
                                //alert("selected page number: " + pageNum);
                                loadWaresForIngredient(ingredientId, callbackHandler, pageNum);
                            });
                            $(this).hover(function() {
                                $(this).addClass("hover_link");
                            }, function() {
                                $(this).removeClass("hover_link");
                            });
                        });
                    }
                } else {
                    alert("Server error");
                }
            },
            error: function(error) {
                alert(error);
                window.location.reload(true);
            }
        });
    };

    var onWaresGroupSelect = function(callbackHandler, groupId, page) {
        $.ajax({
            url: getWaresListUrl,
            type: 'GET',
            dataType: 'json',
            data: { "groupId": groupId, "page": page },
            success: function(reply) {
                if (reply) {
                    if (reply.error) {
                        alert('error:' + reply.error);
                    } else {
                        var waresContainer = $("#wares_list_container_div");
                        waresContainer.html(reply['formHtml']);

                        $(".ware_select_link").each(function() {
                            var wareId = $(this).children(".hidden_id").text();
                            var wareName = $(this).children(".ware_name").text();
                            $(this).click(function() {
                                //alert("selected ware with ID: " + wareId);
                                callbackHandler(wareId, wareName);
                                $(wareDialogContainerSelector).dialog("destroy");
                            });
                            $(this).hover(function() {
                                $(this).addClass("hover_link");
                            }, function() {
                                $(this).removeClass("hover_link");
                            });
                        });
                        $(".page_select_link").each(function() {
                            var pageNum = $(this).children(".hidden_id").text();
                            $(this).click(function() {
                                //alert("selected page number: " + pageNum);
                                onWaresGroupSelect(callbackHandler, groupId, pageNum);
                            });
                            $(this).hover(function() {
                                $(this).addClass("hover_link");
                            }, function() {
                                $(this).removeClass("hover_link");
                            });
                        });
                    }
                } else {
                    alert("Server error");
                }
            },
            error: function(error) {
                alert(error);
                window.location.reload(true);
            }
        });
    };

    // public methods
    // this.onWareDialogLinkClick = onWareDialogLinkClick;

}

function RecipesSelectDialog(recipeDialogContainerId, selectRecipesFormUrl, getRecipesListUrl) {

    var recipeDialogContainerSelector = "#" + recipeDialogContainerId;

//    $(".select_recipe_dialog_link").click(function() {
//        onRecipeDialogLinkClick();
//    });

    var onRecipeDialogLinkClick = function(recipeInputId, recipeNameId, callbackHandler) {
        $(recipeDialogContainerSelector).dialog({
            "modal":true,
            "resizable":false,
            "title": 'select recipe',
            minHeight: 450,
            minWidth: 650
        });
        $.ajax({
            url: selectRecipesFormUrl,
            type: 'GET',
            dataType: 'json',
            success: function(reply) {
                if (reply) {
                    if (reply.error) {
                        alert('error:' + reply.error);
                    } else {
                        //alert(reply['formHtml']);
                        var containerPtr = $(recipeDialogContainerSelector);
                        containerPtr.html(reply['formHtml']);

                        $("#select_recipe_recipes_group_browser").treeview();

                        $(".folder").unbind("click.treeview").add($("a", this)).hoverClass();

                        $(".folder").each(function() {
                            var groupId = $(this).children(".hidden_id").text();
                            var groupType = $(this).children(".hidden_group_type").text();
                            $(this).click(function() {
                                onRecipesGroupSelect(groupId, groupType, 0, recipeInputId, recipeNameId, callbackHandler);
                            });
                        });
                    }
                } else {
                    alert("Server error");
                }
            },
            error: function(error) {
                alert(error);
                window.location.reload(true);
            }
        });
        //alert("show dialog");
    };

    var onRecipesGroupSelect = function(groupId, groupType, page, recipeInputId, recipeNameId, callbackHandler) {
        $.ajax({
            url: getRecipesListUrl,
            type: 'GET',
            dataType: 'json',
            data: { "groupId": groupId, "groupType": groupType, "page": page },
            success: function(reply) {
                if (reply) {
                    if (reply.error) {
                        alert('error:' + reply.error);
                    } else {
                        var recipesContainer = $("#recipes_list_container_div");
                        recipesContainer.html(reply['formHtml']);

                        $(".recipe_select_link").each(function() {
                            var recipeId = $(this).children(".hidden_id").text();
                            var recipeName = $(this).children(".recipe_name").text();
                            $(this).click(function() {
                                //alert("selected recipe with ID: " + recipeId);
                                if (callbackHandler) {
                                    callbackHandler(recipeId, recipeName);
                                } else {
                                    if (recipeInputId) {
                                        $("#" + recipeInputId).val(recipeId);
                                    }
                                    if (recipeNameId) {
                                        $("#" + recipeNameId).html(recipeName);
                                    }
                                }
                                $(recipeDialogContainerSelector).dialog("destroy");
                            });
                            $(this).hover(function() {
                                $(this).addClass("hover_link");
                            }, function() {
                                $(this).removeClass("hover_link");
                            });
                        });
                        $(".page_select_link").each(function() {
                            var pageNum = $(this).children(".hidden_id").text();
                            $(this).click(function() {
                                //alert("selected page number: " + pageNum);
                                onRecipesGroupSelect(groupId, groupType, pageNum, recipeInputId, recipeNameId, callbackHandler);
                            });
                            $(this).hover(function() {
                                $(this).addClass("hover_link");
                            }, function() {
                                $(this).removeClass("hover_link");
                            });
                        });
                        $(".recipe_group_select_link").each(function() {
                            $(this).click(function() {
                                var childGroupId = $(this).children(".hidden_id").text();
                                onRecipesGroupSelect(childGroupId, groupType, 0, recipeInputId, recipeNameId, callbackHandler);
                            });
                            $(this).hover(function() {
                                $(this).addClass("hover_link");
                            }, function() {
                                $(this).removeClass("hover_link");
                            });
                        });
                    }
                } else {
                    alert("Server error");
                }
            },
            error: function(error) {
                alert(error);
                window.location.reload(true);
            }
        });
    };

    // public methods
    this.onRecipeDialogLinkClick = onRecipeDialogLinkClick;

}

function RecipeGroupsSelectDialog(recipeGroupDialogContainerId, selectRecipeGroupsFormUrl) {

    var recipeGroupDialogContainerSelector = "#" + recipeGroupDialogContainerId;

    // public methods
    this.onRecipeGroupDialogLinkClick = function(callbackHandler) {
        $(recipeGroupDialogContainerSelector).dialog({
            "modal":true,
            "resizable":false,
            "title": 'select recipe group',
            minHeight: 450,
            minWidth: 450
        });
        $.ajax({
            url: selectRecipeGroupsFormUrl,
            type: 'GET',
            dataType: 'json',
            success: function(reply) {
                if (reply) {
                    if (reply.error) {
                        alert('error:' + reply.error);
                    } else {
                        //alert(reply['formHtml']);
                        var containerPtr = $(recipeGroupDialogContainerSelector);
                        containerPtr.html(reply['formHtml']);

                        $("#select_recipe_group_recipes_group_browser").treeview();

                        $(".folder").unbind("click.treeview").add($("a", this)).hoverClass();

                        $(".folder").each(function() {
                            var groupId = $(this).children(".hidden_id").text();
                            var groupName = $(this).children(".group_name").text();
                            $(this).click(function() {
                                callbackHandler(groupId, groupName);
                                $(recipeGroupDialogContainerSelector).dialog("destroy");
                            });
                        });
                    }
                } else {
                    alert("Server error");
                }
            },
            error: function(error) {
                alert(error);
                window.location.reload(true);
            }
        });
        //alert("show dialog");
    };
}

function RegionsSelectDialog(regionDialogContainerId, selectRegionsFormUrl) {

    var regionDialogContainerSelector = "#" + regionDialogContainerId;

    // public methods
    this.onRegionDialogLinkClick = function(callbackHandler) {
        $(regionDialogContainerSelector).dialog({
            "modal":true,
            "resizable":false,
            "title": 'select region',
            minHeight: 250,
            minWidth: 450
        });
        $.ajax({
            url: selectRegionsFormUrl,
            type: 'GET',
            dataType: 'json',
            success: function(reply) {
                if (reply) {
                    if (reply.error) {
                        alert('error:' + reply.error);
                    } else {
                        //alert(reply['formHtml']);
                        var containerPtr = $(regionDialogContainerSelector);
                        containerPtr.html(reply['formHtml']);

                        $("#select_region_browser").treeview();

                        $(".select_reg").unbind("click.treeview").add($("a", this)).hoverClass();

                        $(".select_reg").each(function() {
                            var regionId = $(this).children(".hidden_id").text();
                            var regionName = $(this).children(".reg_name").text();
                            $(this).click(function() {
                                callbackHandler(regionId, regionName);
                                $(regionDialogContainerSelector).dialog("destroy");
                            });
                        });
                    }
                } else {
                    alert("Server error");
                }
            },
            error: function(error) {
                alert(error);
                window.location.reload(true);
            }
        });
        //alert("show dialog");
    };
}


function IngredientsSelectDialog(ingredientDialogContainerId, selectIngredientsFormUrl, getIngredientsListUrl) {

    var thisObj = this;

    var ingredientDialogContainerSelector = "#" + ingredientDialogContainerId;

    this.onIngredientDialogLinkClick = function(callbackHandler) {
        $(ingredientDialogContainerSelector).dialog({
            "modal":true,
            "resizable":false,
            "title": 'select ingredient',
            minHeight: 450,
            minWidth: 650
        });
        $.ajax({
            url: selectIngredientsFormUrl,
            type: 'GET',
            dataType: 'json',
            success: function(reply) {
                if (reply) {
                    if (reply.error) {
                        alert('error:' + reply.error);
                    } else {
                        //alert(reply['formHtml']);
                        var containerPtr = $(ingredientDialogContainerSelector);
                        containerPtr.html(reply['formHtml']);

                        $("#ingredients_group_browser").treeview();

/*
                        $(".folder").unbind("click.treeview").bind("click.treeview", function(event) {
                            // don't handle click events on children, eg. checkboxes
                            if ( this == event.target )
                                toggler.apply($(this).next());
                        }).add( $("a", this) ).hoverClass();
*/

//                        $(".folder").unbind("click.treeview").add($("a", this)).hoverClass();
                        $(".folder").add($("a", this)).hoverClass();

                        $(".folder").each(function() {
                            var folderObj = $(this);
                            var groupId = $(this).children(".hidden_id").text();
                            $(this).click(function() {
                                folderObj.append('<span class="placeholder"/>');
                                thisObj.onIngredientsGroupSelect(callbackHandler, groupId, 0);
                                $(".placeholder").remove();
                                if (groupId == '5') {
                                    alert("JOPA");

                                    var branch = $(
                                        '<ul>' +
                                        '<li class="closed"><span class="folder"><span class="hidden_id">111</span>ONE</span></li> ' +
                                        '<li class="closed"><span class="folder"><span class="hidden_id">112</span>TWO</span></li> ' +
                                        '<li class="closed"><span class="folder"><span class="hidden_id">113</span>TRE</span></li> '
                                            +
                                        '</ul>'
                                    );

                                    folderObj.append(branch);
                                    branch.treeview();
                                    //branch.treeview();
                                    //$(".folder").add($("a", this)).hoverClass();
                                }
                            });
                        });
                    }
                } else {
                    alert("Server error");
                }
            },
            error: function(error) {
                alert(error);
                window.location.reload(true);
            }
        });
        //alert("show dialog");
    };

    this.onIngredientsGroupSelect = function(callbackHandler, groupId, page) {
        $.ajax({
            url: getIngredientsListUrl,
            type: 'GET',
            dataType: 'json',
            data: { "groupId": groupId, "page": page },
            success: function(reply) {
                if (reply) {
                    if (reply.error) {
                        alert('error:' + reply.error);
                    } else {
                        var ingredientsContainer = $("#ingredients_list_container_div");
                        ingredientsContainer.html(reply['formHtml']);
                        var ingredients = reply["ingredients"];
                        var defWaresViews = reply["defWaresViews"];
                        $(".ingredient_select_link").each(function() {
                            var ingredientId = $(this).children(".hidden_id").text();
//                            var ingredientName = $(this).children(".ingredient_name").text();
                            $(this).click(function() {
//                                callbackHandler(ingredientId, ingredientName);
                                callbackHandler(ingredients[ingredientId], defWaresViews);
                                $(ingredientDialogContainerSelector).dialog("destroy");
                            });
                            $(this).hover(function() {
                                $(this).addClass("hover_link");
                            }, function() {
                                $(this).removeClass("hover_link");
                            });
                        });
                        $(".page_select_link").each(function() {
                            var pageNum = $(this).children(".hidden_id").text();
                            $(this).click(function() {
                                //alert("selected page number: " + pageNum);
                                thisObj.onIngredientsGroupSelect(ingredientInputId, ingredientNameId, groupId, pageNum);
                            });
                            $(this).hover(function() {
                                $(this).addClass("hover_link");
                            }, function() {
                                $(this).removeClass("hover_link");
                            });
                        });
                    }
                } else {
                    alert("Server error");
                }
            },
            error: function(error) {
                alert(error);
                window.location.reload(true);
            }
        });
    };

}

function WareUserPriceSetDialog(setPriceUrl, dialogDivId, formWareIdInputId, formWareNameSpanId, formWarePriceInputId) {

    var setPriceDialogContainerSelector = "#" + dialogDivId;

    this.bindSubmitPriceAction = function(callbackHandler) {
        $(".submit_price_btn").click(function() {
            var wareId = $("#set_price_form_ware_id").val();
            var warePrice = $("#set_price_form_ware_price").val();

            warePrice = parseFloat(warePrice);
            if (warePrice > 0) {
                $(setPriceDialogContainerSelector).dialog("destroy");
                showLoadingDialog();
                $.ajax({
                    url: setPriceUrl ,
                    type: 'GET',
                    dataType: 'json',
                    data: {
                        "wareId": wareId,
                        "warePrice": warePrice
                    },
                    success: function(reply) {
                        if (reply) {
                            if (reply["result"] == "OK") {
                                callbackHandler(wareId, warePrice);
                            }
                            hideLoadingDialog();
                        } else {
                            alert("server error");
                            window.location.reload(true);
                        }
                    },
                    error: function(error) {
                        alert(error);
                        window.location.reload(true);
                    }
                });
            } else {
                alert("Bad price value");
            }
        });
    };

    this.showDialogForm = function(wareId, wareName, wareCurPriceGetter) {
        $("#" + formWareIdInputId).val(wareId);
        $("#" + formWareNameSpanId).html(wareName);
        $("#" + formWarePriceInputId).val(wareCurPriceGetter());

        $(setPriceDialogContainerSelector).dialog({
            "modal":true,
            "resizable":false,
            "title": 'select your price',
            minHeight: 150,
            minWidth: 400
        });

    };

}

function RecipeSelectCoolDialog(recipeGroupsContainer, recipesContainer, urls, selectRecipeCallback) {

    var ROW_LIMIT = 24;
    var PAGE_SIZE = 5;

    var groupsTree;
    var recipePages = {};
    var totalPagesCount = 0;

    var showRecipesPage = function(pageInfo, groupId, groupType) {

//        recipesContainer.html('');

        var ul = $('<ul class="recipes_list"/>');

        $.each(pageInfo.recipes, function(index, recipe) {
            var li = $('<li class="recipe_link"/>')
                .append($('<span>' + recipe.name + '</span>'));

            ul.append(li);

            li.click(function() {
                selectRecipeCallback(recipe);
            });

        });

        recipesContainer.html(ul);

//        alert(pageInfo);
    };

    var loadRecipesForGroup = function(groupId, groupType, page) {
        if (recipePages) {
            var pageInfo = recipePages['page_' + page];
            if (pageInfo) {
                showRecipesPage(pageInfo, groupId, groupType);
                return;
            }
        }
        var getRecipesUrl;
        switch (groupType) {
            case 'COMMON':
                getRecipesUrl = urls.getCommonRecipesUrl;
                break;
            case 'USER':
                getRecipesUrl = urls.getUserRecipesUrl;
                break;
        }
        showLoadingDialog();
        $.ajax({
            url: getRecipesUrl,
            type: 'GET',
            dataType: 'json',
            data: {
                "groupId": groupId,
                "rowLimit": ROW_LIMIT,
                "pageSize": PAGE_SIZE,
                "page": page
            },
            success: function(reply) {
                if (reply) {
                    var pages = reply.pages;
                    if (totalPagesCount != reply.totalPagesCount) {
                        totalPagesCount = reply.totalPagesCount;
                        recipePages = {};
                    }
                    $.each(pages, function(index, pageInfo) {
                        recipePages['page_' + pageInfo.page] = pageInfo;
                    });
                    loadRecipesForGroup(groupId, groupType, page);
                    hideLoadingDialog();
                } else {
                    alert("Server error(1)");
                    window.location.reload(true);
                }
            },
            error: function(error) {
                alert("Server error(2)");
                window.location.reload(true);
            }
        });
    };

    var addLevel = function (container, data) {

        var showChildrenUl = function(li, hitarea, ul) {
            hitarea.addClass('collapsable-hitarea');
            hitarea.removeClass('expandable-hitarea');
            // li.removeClass('expandable');
            ul.show();
        };

        var hideChildrenUl = function(li, hitarea, ul) {
            hitarea.removeClass('collapsable-hitarea');
            hitarea.addClass('expandable-hitarea');
            // li.addClass('expandable');
            ul.hide();
        };

        var loadChildren = function(parentId) {
            var testChildren = [
                {id: 'chld-1-for-' + parentId, title: 'chld-1-for-' + parentId, folder: false},
                {id: 'chld-2-for-' + parentId, title: 'chld-2-for-' + parentId, folder: false},
                {id: 'chld-3-for-' + parentId, title: 'chld-3-for-' + parentId, folder: true, closed: true,
                    children: [
                        {id: 'chld-3-1-for-' + parentId, title: 'chld-3-1-for-' + parentId, folder: false},
                        {id: 'chld-3-2-for-' + parentId, title: 'chld-3-2-for-' + parentId, folder: false},
                        {id: 'chld-3-3-for-' + parentId, title: 'XXXXXXXXXXXXXXXXXXXXXXXXXX-chld-3-3-for-' + parentId, folder: false}
                    ]
                }
            ];
//            alert('going to load children');
//            alert('children loaded');
            return testChildren;
        };

        $.each(data, function(index, value) {
            //alert('2');
            var nodeId = value.id;
            var groupId = value.groupId;
            var groupType = value.groupType;
            var nodeTitle = $('<span>' + value.title +'</span>').text();
            var nodeIsFolder = value.folder;
            var hasChildren = value.folder ? value.children.length > 0 : false;
            var folderClosed = value.closed;
            var nodeNeedLoadChildren = false;

            var li = $('<li/>');
            li.addClass('expandable');
            container.append(li);

            var spans = $('<span class="recipeGroupSpan"><span class="hidden_id">' + nodeId + '</span>' + nodeTitle +'</span>');
            spans.addClass(nodeIsFolder ? "folder" : "file");

            var ul = $('<ul/>');

            var toggleItem = function() {
                if (nodeNeedLoadChildren) {
                    li.append('<span class="placeholder"/>');
//                    alert('111');
                    value['children'] = loadChildren(nodeId);
                    $(".placeholder").remove();
                    addLevel(ul, value['children']);
                    nodeNeedLoadChildren = false;
//                        alert('111');
                }
                if (ul.is(":visible")) {
                    hideChildrenUl(li, hitarea, ul);
                } else {
                    showChildrenUl(li, hitarea, ul);
                }
            };
            if (nodeIsFolder && hasChildren) {
                var hitarea = $('<div class="hitarea collapsable-hitarea"></div>');
                hitarea.click(function() {
                    toggleItem();
                });
                li.append(hitarea);
                if (folderClosed || nodeNeedLoadChildren) {
                    hideChildrenUl(li, hitarea, ul);
                }
            }
            spans.click(function() {
                var idOfNode = $(this).children(".hidden_id").text();
                if (value.folder) {
                    if (!$(this).hasClass("selectedRecipeGroup")) {
                        $(".recipeGroupSpan").removeClass("selectedRecipeGroup");
                        $(this).addClass("selectedRecipeGroup");
                        recipePages = {};
                    }
                    loadRecipesForGroup(groupId, groupType, 0);
                } else {
                    // alert('id file: ' + idOfNode);
                    if (li.hasClass("selected")) {
                        li.removeClass("selected");
                    } else {
                        li.addClass("selected");
                    }
                }
            });


            li.append(spans);
            if (nodeIsFolder && hasChildren) {
                li.append(ul);
                if (!nodeNeedLoadChildren) {
                    addLevel(ul, value['children']);
                }
            }

        });
    };


    var drawGroupsTree = function(groupsTree) {
        var ul = $('<ul/>');
        recipeGroupsContainer.append(ul);
        recipeGroupsContainer.innerHTML = '';
        addLevel(ul, groupsTree);
    };

    this.initContainers = function() {

        showLoadingDialog();
        $.ajax({
            url: urls.getGroupsUrl,
            type: 'GET',
            dataType: 'json',
            success: function(reply) {
                if (reply) {
                    groupsTree = reply.result;
                    drawGroupsTree(groupsTree);
                    hideLoadingDialog();
                } else {
                    alert("Server error");
                    window.location.reload(true);
                }
            },
            error: function(error) {
                alert('ERROR:');
                alert(error);
                window.location.reload(true);
            }
        });
    }

}

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }
    }

    document.body.appendChild(form);
    form.submit();
}